package org.huiway.huipicturebackend.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.huiway.huipicturebackend.annotation.AuthCheck;
import org.huiway.huipicturebackend.common.BaseResponse;
import org.huiway.huipicturebackend.common.ResultUtils;
import org.huiway.huipicturebackend.constant.UserConstant;
import org.huiway.huipicturebackend.exception.BusinessException;
import org.huiway.huipicturebackend.exception.ErrorCode;
import org.huiway.huipicturebackend.manager.CosManager;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
    @Resource
    private CosManager cosManager;
    /**
     * 测试文件上传
     *
     * @param multipartFile
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {   //通过formdata来上传文件
        // 文件目录
        String filename = multipartFile.getOriginalFilename();  //当前用户传的文件名称
        String filepath = String.format("/test/%s", filename);  //指定将上传到对象存储的哪个位置
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);  //创建一个临时文件，指定临时文件的路径和后缀
            multipartFile.transferTo(file);  //将multipartFile对象传输到本地临时文件中，成为file对象
            cosManager.putObject(filepath, file);  //将文件上传到对象存储 接收 （key,file对象），multipartFile不是file对象
            // 返回可访问地址
            return ResultUtils.success(filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    /**
     * 测试文件下载
     *
     * @param filepath 文件路径
     * @param response 响应对象
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download/")
    public void testDownloadFile(String filepath , HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInput = null;
        try {
            COSObject cosbject = cosManager.getObject(filepath);
            cosObjectInput = cosbject.getObjectContent();
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);// 将输入流转换为字节数组
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");  //浏览器根据响应头的形式判断是浏览图片还是下载图片
            response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
            // 将文件内容写入响应
            response.getOutputStream().write(bytes);
            // 刷新缓冲区
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            //释放流
            if(cosObjectInput != null){
                cosObjectInput.close();
            }
        }

    }

}
